package com.ruoyi.collect.hydrology.manager;

import com.ruoyi.collect.hydrology.model.CollectorMapperDto;
import com.ruoyi.collect.hydrology.model.FileDto;
import com.ruoyi.collect.hydrology.service.CollectParser;
import com.ruoyi.common.utils.SnowflakeIdUtils;
import com.ruoyi.hydrology.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
public class SwjcParser extends CollectParser {

    public SwjcParser(CollectorMapperDto mapperDto, final Charset charset) {
        mapper = mapperDto;
        this.charset = charset;
    }

    @Override
    public void parse(final List<FileDto> files) {
        Stream.of((Consumer<List<FileDto>>) this::analyzeCddyFile,
                this::analyzeCdssFile
        ).parallel().forEach(a -> tryAnalyze(a, files));

    }

    protected String getFileNameRegex(final String type) {
        return String.join("", "(\\d+)_", type, "_(\\d{14}).txt");
    }

    protected String getDatum(String[] data, int index) {
        if (data == null || data.length <= index) {
            log.warn("null[{}]: {}", data, index);
            return null;
        }
        String datum = data[index];
        if (!StringUtils.hasText(datum)) {
            log.warn("empty[{}]: {}", data, index);
        }
        return datum.trim();
    }

    protected BigDecimal getDecimal(String[] data, int index) {
        Logger log = LoggerFactory.getLogger(this.getClass());
        if (data == null || data.length <= index || data[index] == null) {
            log.warn("Invalid data or index: data = {}, index = {}", data, index);
            return null;
        }

        String datum = data[index].trim();
        if (!StringUtils.hasText(datum)) {
            log.warn("Empty value at index {}: data = {}", index, data);
            return null;
        }

        try {
            // 将字符串转换为 Decimal
            BigDecimal value = new BigDecimal(datum);
            return value;
        } catch (NumberFormatException e) {
            log.warn("Failed to convert value at index {}: data = {}", index, data, e);
            return null;
        }
    }
    private String getType(final String type) {
        if (type == null) {
            return "其它类型";
        }
        switch (type) {
            case "0501":
                return "降水量";
            case "0502":
                return "水位";
            case "0507":
                return "水温";
            case "0503":
                return "涌水量";
            case "0504":
                return "排水量";
            case "0505":
                return "地表沉陷位移";
            case "0506":
                return "疏（放）水量";
            case "0607":
                return "微震（水文）";
        }
        return "其它类型";
    }
    private String getUnit(final String type) {
        if (type == null) {
            return "";
        }
        switch (type) {
            case "0501":
                return "mm";
            case "0502":
                return "m";
            case "0507":
                return "℃";
            case "0503":
                return "m³/h";
            case "0504":
                return "m³/h";
            case "0505":
                return "";
            case "0506":
                return "m³/h";
            case "0607":
                return "";
        }
        return "";
    }
    private String getStatus(final String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "00000000":
                return "正常";
            case "00000001":
                return "报警";
            case "00000010":
                return "未知";
            case "00000100":
                return "分站故障";
            case "00001000":
                return "传感器故障";
            case "00010000":
                return "蓝色预警";
            case "001000000":
                return "黄色预警";
            case "01000000":
                return "橙色预警";
            case "1000000":
                return "红色预警";
        }
        return "";
    }

    private String getLevel(final String level) {
        if (level == null) {
            return "";
        }
        switch (level) {
            case "1":
                return "红";
            case "2":
                return "橙";
            case "3":
                return "黄";
            case "4":
                return "蓝";
        }
        return "";
    }
    private void analyzeCddyFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<FileDto>>) this::analyzeCgkCddy,
                this::analyzeJslCddy,
                this::analyzePslCddy,
                this::analyzeYslCddy
        ).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeCgkCddy(final List<FileDto> fileInfos) {
        analyze("CGJCDDY", fileInfos, this::analyzeCgkCddy);
    }


    private void analyzeCgkCddy(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines,0);
                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        // 检查第二个部分的字段数量
                        if (data.length < 10) {
                            // 如果字段数量不足，跳过该行
                            log.warn("Invalid data: {}", line);
                            continue;
                        }
                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String type = getDatum(data, 1);
                        if (type != null){
                            type = getType(type);
                        }
                        String location = getDatum(data, 2);
                        String level = getDatum(data, 3);
                        BigDecimal hight = getDecimal(data, 4);
                        BigDecimal deep = getDecimal(data, 5);
                        BigDecimal holeDeep = getDecimal(data, 6);
                        BigDecimal holeD = getDecimal(data, 7);
                        BigDecimal x = getDecimal(data, 8);
                        BigDecimal y = getDecimal(data, 9);
                        BigDecimal z = getDecimal(data, 10);
//                    String levelBlue = getDatum(data, 11);
//                    String levelYellow = getDatum(data, 12);
//                    String levelOrange = getDatum(data, 13);
//                    String levelRed = getDatum(data, 14);
//                    BigDecimal temperatureBlue = getDecimal(data, 15);
//                    BigDecimal temperatureYellow = getDecimal(data, 16);
//                    BigDecimal temperatureOrange = getDecimal(data, 17);
//                    BigDecimal temperatureRed = getDecimal(data, 18);
                        String date = getDatum(data, 11);
                        Cgkcddy cd = new Cgkcddy();
                        if (date != null){
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            date1 = sdf.parse(date);
                            cd.setInstallationDate(date1);
                        }
                        cd.setStationCode(code);
                        cd.setSensorType(type);
                        cd.setEquipmentPosition(location);
                        cd.setWaterLayerLevel(level);
                        cd.setWaterLayerThickness(hight);
                        cd.setWaterLayerDepth(deep);
                        cd.setDrillName(location + "长观孔" + type);
                        cd.setHoleDepth(holeDeep);
                        cd.setAperture(holeD);
                        cd.setCoordinateX(x);
                        cd.setCoordinateY(y);
                        cd.setCoordinateZ(z);
//                    cd.setWaterLevelWarningBlue(levelBlue);
//                    cd.setWaterLevelWarningYellow(levelYellow);
//                    cd.setWaterLevelWarningOrange(levelOrange);
//                    cd.setWaterLevelWarningRed(levelRed);
//                    cd.setWaterTemperatureWarningBlue(temperatureBlue);
//                    cd.setWaterTemperatureWarningYellow(temperatureYellow);
//                    cd.setWaterTemperatureWarningOrange(temperatureOrange);
//                    cd.setWaterTemperatureWarningRed(temperatureRed);
                        cd.setStationMine(mineCode);
                        cd.setInstallationDate(new Date());
                        Cgkcddy cgkcddy = mapper.getCgkcddyService().selectCgkcddyByCode(code);
                        if (cgkcddy != null){
                            cd.setId(cgkcddy.getId());
                            mapper.getCgkcddyService().updateCgkcddy(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getCgkcddyService().insertCgkcddy(cd);
                        }
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }

                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
        }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }


    protected void analyzeJslCddy(final List<FileDto> fileInfos) {
        analyze("JSLCDDY", fileInfos, this::analyzeJslCddy);
    }
    private void analyzeJslCddy(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");

            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留

                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);
                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 8) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }
                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String type = getDatum(data, 1);
                        String location = getDatum(data, 2);
                        String date = getDatum(data, 3);
                        String fact = getDatum(data, 4);
                        String date2 = getDatum(data, 5);
                        BigDecimal x = getDecimal(data, 6);
                        BigDecimal y = getDecimal(data, 7);
                        BigDecimal z = getDecimal(data, 8);
                        Jslcddy cd = new Jslcddy();
                        if (date != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            date1 = sdf.parse(date);
                            cd.setInstallationDate(date1);
                        }
                        if (date2 != null) {
                            Date date3 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            date3 = sdf.parse(date2);
                            cd.setInspectionDate(date3);
                        }
                        cd.setStationMine(mineCode);
                        cd.setStationCode(code);
                        cd.setEquipmentPosition(location);
                        cd.setEquipmentType(type);
                        cd.setManufacturer(fact);
                        cd.setCoordinateX(x);
                        cd.setCoordinateY(y);
                        cd.setCoordinateZ(z);
                        cd.setMeasureTime(new Date());
                        Jslcddy jslcddy = mapper.getJslcddyService().selectJslcddyByCode(code);
                        if (jslcddy != null){
                            cd.setId(jslcddy.getId());
                            mapper.getJslcddyService().updateJslcddy(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getJslcddyService().insertJslcddy(cd);
                        }
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
        }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }
    protected void analyzePslCddy(final List<FileDto> fileInfos) {
        analyze("PSLCDDY", fileInfos, this::analyzePslCddy);
    }
    private void analyzePslCddy(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);

                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 11) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }

                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String location = getDatum(data, 1);
                        String area = getDatum(data, 2);
                        BigDecimal x = getDecimal(data, 3);
                        BigDecimal y = getDecimal(data, 4);
                        BigDecimal z = getDecimal(data, 5);
                        String house = getDatum(data, 6);
                        String name = getDatum(data, 7);
                        BigDecimal efficiency = getDecimal(data, 8);
                        BigDecimal flow = getDecimal(data, 9);
                        String type = getDatum(data, 10);
//                    BigDecimal blue = getDecimal(data, 11);
//                    BigDecimal yellow = getDecimal(data, 12);
//                    BigDecimal orange = getDecimal(data, 13);
//                    BigDecimal red = getDecimal(data, 14);
//                    BigDecimal max = getDecimal(data, 15);
                        String date = getDatum(data, 11);
                        Pslcddy cd = new Pslcddy();
                        if (data != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            date1 = sdf.parse(date);
                            cd.setInstallationDate(date1);
                        }

                        cd.setStationCode(code);
                        cd.setEquipmentPosition(location);
                        cd.setCoverageArea(area);
                        cd.setCoordinateX(x);
                        cd.setCoordinateY(y);
                        cd.setCoordinateZ(z);
                        cd.setPumpHouse(house);
                        cd.setPumpName(name);
                        cd.setPumpEfficiency(efficiency);
                        cd.setRatedFlow(flow);
                        cd.setPumpType(type);
//                    cd.setDisplacementWarningBlue(blue);
//                    cd.setDisplacementWarningYellow(yellow);
//                    cd.setDisplacementWarningOrange(orange);
//                    cd.setDisplacementWarningRed(red);
//                    cd.setMaxValue(max);

                        cd.setStationMine(mineCode);
                        cd.setInstallationDate(new Date());
                        Pslcddy pslcddy = mapper.getPslcddyService().selectPslcddyByCode(code);
                        if (pslcddy != null){
                            cd.setId(pslcddy.getId());
                            mapper.getPslcddyService().updatePslcddy(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getPslcddyService().insertPslcddy(cd);
                        }
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }

        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }
    protected void analyzeYslCddy(final List<FileDto> fileInfos) {
        analyze("YSLCDDY", fileInfos, this::analyzeYslCddy);
    }
    private void analyzeYslCddy(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;
        String[] lines = content.split("\\|\\|");
            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);

                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");

                        if (data.length < 8) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }
                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String location = getDatum(data, 1);
                        String area = getDatum(data, 2);
                        String type = getDatum(data, 3);
                        String unit = getDatum(data, 4);
                        BigDecimal x = getDecimal(data, 5);
                        BigDecimal y = getDecimal(data, 6);
                        BigDecimal z = getDecimal(data, 7);
                        String date = getDatum(data, 8);
                        Yslcddy cd = new Yslcddy();
                        if (date != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            date1 = sdf.parse(date);
                            cd.setInstallationDate(date1);
                        }
                        cd.setStationCode(code);
                        cd.setEquipmentPosition(location);
                        cd.setCoverageArea(area);
                        cd.setSensorType(type);
                        cd.setUnit(unit);
                        cd.setCoordinateX(x);
                        cd.setCoordinateY(y);
                        cd.setCoordinateZ(z);
                        cd.setStationMine(mineCode);
                        cd.setInstallationDate(new Date());
                        Yslcddy yslcddy = mapper.getYslcddyService().selectYslcddyByCode(code);
                        if (yslcddy != null){
                            cd.setId(yslcddy.getId());
                            mapper.getYslcddyService().updateYslcddy(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getYslcddyService().insertYslcddy(cd);
                        }
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }
    private void analyzeCdssFile(List<FileDto> FileDtos) {
        List<FileDto> FileDto = FileDtos.stream()
                .filter(f -> StringUtils.hasLength(f.getFileName()) && f.getFileName().length() > 18)
                .sorted(Comparator.comparing(f -> f.getFileName().substring(f.getFileName().length() - 18)))
                .collect(Collectors.toList());

        Stream.of((Consumer<List<FileDto>>) this::analyzeCgkCdss,
                this::analyzeJslCdss,
                this::analyzePslCdss,
                this::analyzeYslCdss
        ).parallel().forEach(a -> tryAnalyze(a, FileDto));
    }

    protected void analyzeCgkCdss(final List<FileDto> fileInfos) {
        analyze("CGJCDSS", fileInfos, this::analyzeCgkCdss);
    }
    private void analyzeCgkCdss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;

        String[] lines = content.split("\\|\\|");

            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);
                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 4) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }

                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
//                    String type = getDatum(data, 1);
//                    String location = getDatum(data,2);
                        String status = getDatum(data, 1);
                        BigDecimal level = getDecimal(data, 2);
                        BigDecimal temp = getDecimal(data, 3);
//                    String levelUnit = getDatum(data, 6);
//                    String tempUnit = getDatum(data, 7);
                        String date = getDatum(data, 4);
                        Cgkcdss cd = new Cgkcdss();
                        if (status != null) {
                            int n = Integer.parseInt(status);
                            String s = Integer.toBinaryString(n);
                            while (s.length() < 8) {
                                s = "0" + s;
                            }
                            status = getStatus(s);
                            cd.setPointStatus(status);
                        }
                        if (date != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date1 = sdf.parse(date);
                            cd.setMonitorTime(date1);
                        }
                        cd.setStationCode(code);
//                    cd.setSensorType(type);
//                    cd.setLocation(location);
                        cd.setWaterLevel(level);
                        cd.setWaterTemperature(temp);
//                    cd.setWaterLevelUnit(levelUnit);
//                    cd.setWaterTemperatureUnit(tempUnit);
                        cd.setOrgCode(mineCode);
                        cd.setMonitorTime(new Date());
                        Cgkcdss cgkcdss = mapper.getCgkcdssService().selectCgkcdssByCode(code);
                        if (cgkcdss != null){
                            cd.setId(cgkcdss.getId());
                            mapper.getCgkcdssService().updateCgkcdss(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getCgkcdssService().insertCgkcdss(cd);
                        }
                        CgkcdssHistory cgkcdssHistory = new CgkcdssHistory();
                        BeanUtils.copyProperties(cd,cgkcdssHistory);
                        cgkcdssHistory.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getCgkcdssHistoryService().insertCgkcdssHistory(cgkcdssHistory);
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected void analyzeJslCdss(final List<FileDto> fileInfos) {
        analyze("JSLCDSS", fileInfos, this::analyzeJslCdss);
    }
    private void analyzeJslCdss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;

        String[] lines = content.split("\\|\\|");
            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);

                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 5) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }

                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String clear = getDatum(data, 1);
                        String ce = getDatum(data, 2);
                        String time = getDatum(data, 3);
                        String status = getDatum(data, 4);
                        BigDecimal value = getDecimal(data, 5);
                        Jslcdss cd = new Jslcdss();
                        if (clear != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date1 = sdf.parse(clear);
                            cd.setClearTime(date1);
                        }
                        if (ce != null) {
                            Date date2 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date2 = sdf.parse(ce);
                            cd.setMeasureTime(date2);
                        }
                        if (time != null) {
                            Date date3 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date3 = sdf.parse(time);
                            cd.setMonitorTime(date3);
                        }
                        cd.setStationCode(code);
                        cd.setValue(value);
                        cd.setStationMine(mineCode);
                        if (status != null) {
                            int n = Integer.parseInt(status);
                            String s = Integer.toBinaryString(n);
                            while (s.length() < 8) {
                                s = "0" + s;
                            }
                            status = getStatus(s);
                            cd.setStationStatus(status);
                        }
                        cd.setMonitorTime(new Date());
                        Jslcdss jslcdss = mapper.getJslcdssService().selectJslcdssByCode(code);
                        if (jslcdss != null){
                            cd.setId(jslcdss.getId());
                            mapper.getJslcdssService().updateJslcdss(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getJslcdssService().insertJslcdss(cd);
                        }
                        JslcdssHistory jslcdssHistory = new JslcdssHistory();
                        BeanUtils.copyProperties(cd,jslcdssHistory);
                        jslcdssHistory.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getJslcdssHistoryService().insertJslcdssHistory(jslcdssHistory);
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected void analyzePslCdss(final List<FileDto> fileInfos) {
        analyze("PSLCDSS", fileInfos, this::analyzePslCdss);
    }
    private void analyzePslCdss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;

        String[] lines = content.split("\\|\\|");
            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);

                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 4) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }
                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
                        String location = getDatum(data, 1);
                        String status = getDatum(data, 2);
                        BigDecimal value = getDecimal(data, 3);
                        String time = getDatum(data, 4);
                        Pslcdss cd = new Pslcdss();
                        if (time != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date1 = sdf.parse(time);
                            cd.setMonitorTime(date1);
                        }
                        cd.setStationCode(code);
                        cd.setValue(value);
                        cd.setLocation(location);
                        cd.setStationMine(mineCode);
                        if (status != null) {
                            int n = Integer.parseInt(status);
                            String s = Integer.toBinaryString(n);
                            while (s.length() < 8) {
                                s = "0" + s;
                            }
                            status = getStatus(s);
                            cd.setStationStatus(status);
                        }
                        cd.setMonitorTime(new Date());
                        Pslcdss pslcdss = mapper.getPslcdssService().selectPslcdssByCode(code);
                        if (pslcdss != null){
                            cd.setId(pslcdss.getId());
                            mapper.getPslcdssService().updatePslcdss(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getPslcdssService().insertPslcdss(cd);
                        }
                        PslcdssHistory pslcdssHistory = new PslcdssHistory();
                        BeanUtils.copyProperties(cd,pslcdssHistory);
                        pslcdssHistory.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getPslcdssHistoryService().insertPslcdssHistory(pslcdssHistory);
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

    protected void analyzeYslCdss(final List<FileDto> fileInfos) {
        analyze("YSLCDSS", fileInfos, this::analyzeYslCdss);
    }
    private void analyzeYslCdss(final List<String> matches, final String content, FileDto fileInfo) {
        long begin = System.currentTimeMillis();
        int count = 0;

        String[] lines = content.split("\\|\\|");
            for (String line : lines) {
                try {
                    String[] parts = line.split("~", -1); // 使用 -1 参数确保空字段也被保留
                    if (parts.length < 2) {
                        // 如果字段数量不足，跳过该行
                        log.warn("Invalid line: {}", line);
                        continue;
                    }
                    for (int i = 1; i < parts.length; i++) {
                        // 第一个部分处理
                        String[] mines = parts[0].split(";");
                        String mineCode = getDatum(mines, 0);

                        // 第二个部分使用 ';' 分割
                        String[] data = parts[i].split(";");
                        if (data.length < 3) {
                            log.info("data_invalid: [{}]", line);
                            continue;
                        }
                        long start = System.currentTimeMillis();
                        String code = getDatum(data, 0);
//                    String type = getDatum(data, 1);
//                    String location = getDatum(data, 2);
                        String status = getDatum(data, 1);
                        String value = getDatum(data, 2);
//                    String unit = getDatum(data, 5);
                        String time = getDatum(data, 3);
                        Yslcdss cd = new Yslcdss();
                        if (time != null) {
                            Date date1 = null;
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            date1 = sdf.parse(time);
                            cd.setMonitorTime(date1);
                        }
//                    cd.setSensorType(type);
                        cd.setPointCode(code);
//                    cd.setLocation(location);
//                    cd.setUnit(unit);
                        cd.setValue(value);
                        cd.setStationMine(mineCode);
                        if (status != null) {
                            int n = Integer.parseInt(status);
                            String s = Integer.toBinaryString(n);
                            while (s.length() < 8) {
                                s = "0" + s;
                            }
                            status = getStatus(s);
                            cd.setPointStatus(status);
                        }
                        cd.setMonitorTime(new Date());
                        Yslcdss yslcdss = mapper.getYslcdssService().selectYslcdssByCode(code);
                        if (yslcdss != null){
                            cd.setId(yslcdss.getId());
                            mapper.getYslcdssService().updateYslcdss(cd);
                        }else {
                            cd.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                            mapper.getYslcdssService().insertYslcdss(cd);
                        }
                        YslcdssHistory yslcdssHistory = new YslcdssHistory();
                        BeanUtils.copyProperties(cd,yslcdssHistory);
                        yslcdssHistory.setId(String.valueOf(new SnowflakeIdUtils(5,8).nextId()));
                        mapper.getYslcdssHistoryService().insertYslcdssHistory(yslcdssHistory);
                        log.info("cost:" + (System.currentTimeMillis() - start));

                        count++;
                    }
                } catch (Exception e) {
                    log.warn("", e);
                    log.warn("analyze_fail:[{}]", line);
                }
            }
        log.info("end_collect: [{}-{}] [{}]", fileInfo.getFileName(), count, System.currentTimeMillis() - begin);
        fileInfo.setAnalyzed(true);
    }

}
